local filename = "bindagencyrid.lua"
local skynet = require "skynet"
local tostring = tostring
local filelog = require "filelog"
local cluster = require "skynet.cluster"
local timetool = require "timetool"
local md5 = require "md5"
local configdao = require "configdao"

local json = require "cjson.safe"
json.encode_sparse_array(true,1,1)

require "pubenum"

local service = nil
local CMD = {
	service = nil
}


local function check_agencyrid(rid, agencyrid, pkgid)
	if not agencyrid or agencyrid <= 0 then
		return false
	end
	local status,result = skynet.pcall(skynet.call, ".mainnode", "lua", "cmd", "send_bindagency_request", rid, agencyrid, pkgid)
    if not status or not result then
        return false
    end
    local result_data = json.decode(result)
    if result_data.code == 0 and agencyrid == result_data.data.agnecy_rid then
    	return true, result_data.data.msg
    else
    	return false
    end
end

function CMD.process(rid, msgbody)
	if not service then
		service = CMD.service
	end
	if not msgbody or not msgbody.agencyrid or msgbody.agencyrid <= 0 then
		return { retcode = EErrCode.ERR_INVALID_PARAMS, retstr = "上级id无效!"}
	end
	---判断是否是一个代理
	--发送http请求
	local pkgid = service.info.pkgid
    local result, result_str = check_agencyrid(rid, msgbody.agencyrid, pkgid)
    --filelog.sys_error("--------bindagencyrid------check_agencyrid--------", rid, "-------msgbody---", msgbody,"---result---", result)
    if not result then
        return { retcode = EErrCode.ERR_INVALID_PARAMS, retstr = result_str or "上级玩家数据有误" }
    end
	service.info.agencyrid = msgbody.agencyrid
	cluster.call("datanode", ".router", "update_rk", rid, "rs_info", 0, {agencyrid = msgbody.agencyrid})
	local cmdstr = json.encode({msghead={msgname="bind_agencyrid"}, msgbody={uid=serviceuid, aid = msgbody.agencyrid, rid=rid}})
	-- redisdao.query_data(".gmmqredis", "rpush", "responsemq", cmdstr)
	skynet.send(".gamedatalog", "lua", "write", cmdstr)
	return {}
end

return CMD